<template>
    <div class="user-set-page">
        <fieldset class="user-info-group">
            <div class="form-item">
                <div id="nickname">
                    <label for="nickname">昵称：</label>
                    <el-input v-model="userInfo.username" :placeholder="userInfo.username ? userInfo.username : '输入昵称'"
                        clearable @blur="handleBlur('username')"></el-input>
                </div>
                <div id="avatar">
                    <input type="file" ref="fileInput" style="display: none;" @change="handleFileUpload">
                    <el-button plain size="large" style="width: 70px;" @click="fileInput?.click()">更换头像</el-button>
                    <n-avatar :src="userInfo.avatar" />
                </div>
            </div>
            <div class="form-item">
                <label for="signature">个签：</label>
                <n-input v-model:value="userInfo.signatureOfTheIndividual"
                    :placeholder="userInfo.signatureOfTheIndividual == null ? '设置属于自己的个性签名~' : userInfo.signatureOfTheIndividual"
                    :minlength="5" :maxlength="30" show-count clearable
                    @input-blur="handleBlur('signatureOfTheIndividual')" />
            </div>
            <div class="form-item">
                <label for="sex">性别：</label>
                <el-radio-group v-model="userInfo.gex" size="default">
                    <el-radio v-for="gex in gexes" :key="gex.value" :value="gex.value" border>{{ gex.label }}</el-radio>
                </el-radio-group>
            </div>
            <div class="form-item">
                <label for="birthday">生日：</label>
                <el-date-picker v-model="userInfo.birthday"
                    :placeholder="userInfo.birtyday === null ? '填写生日' : userInfo.birthday" clearable
                    @blur="handleBlur('birthday')"></el-date-picker>
            </div>
            <div class="form-item">
                <label for="country">国家：</label>
                <el-select v-model="userInfo.country"
                    :placeholder="userInfo.country === null ? '选择国家' : userInfo.country" @blur="handleBlur('country')">
                    <el-option v-for="country in countryOptions" :key="country.value" :label="country.label"
                        :value="country.value">
                        <span style="margin-left: 6px;">{{ country.label }}</span>
                    </el-option>
                </el-select>
            </div>
            <div class="form-item">
                <div id="province">
                    <label for="province">省份：</label>
                    <el-select v-model="userInfo.province"
                        :placeholder="userInfo.province === null ? '选择省份' : userInfo.province" clearable
                        @blur="handleBlur('province')">
                        <el-option v-for="province in provinceOptions" :key="province.value" :label="province.label"
                            :value="province.value">
                            <span style="margin-left: 6px;">{{ province.label }}</span>
                        </el-option>
                    </el-select>
                </div>
                <div id="city">
                    <label for="city">城市：</label>
                    <el-select v-model="userInfo.city" :placeholder="userInfo.city === null ? '选择城市' : userInfo.city"
                        clearable @blur="handleBlur('city')">
                        <el-option v-for="city in currentCities" :key="city.value" :label="city.label"
                            :value="city.value">
                            <span style="margin-left: 6px;">{{ city.label }}</span>
                        </el-option>
                    </el-select>
                </div>
            </div>
        </fieldset>
        <div class="dispose-btns">
            <el-button type="primary" link @click="saveUserInfo">保存</el-button>
        </div>
    </div>
</template>


<script setup lang="ts">
import { cityData, countryOptions, provinceOptions } from '@/components/General/Setting/UserSet/user';
import { userStore } from '@/store/userStore';
import { ElMessage } from 'element-plus';
import axiosInstance from "@utils/axiosInstance"
import { computed, onMounted, reactive, ref, watch } from 'vue';


// 创建一个深拷贝，确保原始对象内容不会被修改           主要用于存储用户修改的信息
const userInfo = ref(JSON.parse(JSON.stringify(userStore().userInfo)));
// 记录用户修改的字段
const modifiedFields = reactive<Set<string>>(new Set());


const fileInput = ref<HTMLInputElement | null>(null);
const avatarPreview = ref<string>("");

// 处理失焦事件
function handleBlur(field: string) {
    modifiedFields.add(field);
}

// 根据选择的省份动态获取城市列表
const currentCities = computed(() => {
    if (!userInfo.value.province) return [];
    return cityData[userInfo.value.province] || [];
})

// 上传文件     在这里也记录修改（先粗略存储，后面再优化，只有当值发生变化再修改）
async function handleFileUpload(event: Event): Promise<void> {
    modifiedFields.add('avatar');
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];
    if (!file) return;

    if (!file.type.startsWith('image/')) {
        ElMessage.warning("请选择图片文件");
        return;
    }
    if (file.size > 2 * 1024 * 1024) {       // 2MB限制
        ElMessage.warning("图片大小不能超过2MB");
        return;
    }
    try {
        const userStoreInstance = userStore();
        // 本地预览
        const reader = new FileReader();
        reader.onload = (e) => {
            avatarPreview.value = e.target?.result as string;
        }
        reader.readAsDataURL(file);

        // 实际文件上传
        const formData = new FormData();
        formData.append("userId", userStore().userInfo.uu_id);
        formData.append("avatarFile", file);
        const response = await axiosInstance.post<{
            success: boolean, url?: string, message?: string
        }>("http://localhost:8080/file/upload-avatar", formData, {
            headers: {
                'Content-Type': "multipart/form-data"
            }
        });

        if (response && response.data && response.data.success) {
            userStoreInstance.userInfo.avatar = response.data.url as string;
            // 手动触发更新  不要破坏响应式
            userInfo.value['avatar'] = response.data.url as string;
        } else {
            ElMessage.warning("解析文件出现异常");
        }

    } catch (error: any) {
        ElMessage.error("文件上传失败");
        console.error(error)
    } finally {
        // 重置input，允许重复选择同一文件
        if (target) target.value = '';
    }
}

const gexes = reactive<{ label: string; value: string }[]>([
    { label: "男", value: "boy" }, { label: "女", value: "girl" }, { label: "未知", value: "unknown" }
])


// 通过监听用户性别信息来动态更新
watch(() => userInfo.value.gex, (newGex: string, oldGex: string) => {
    if (newGex && newGex !== oldGex) {
        modifiedFields.add('gex');
    }
})

// 保存按钮
const saveUserInfo = async (): Promise<void> => {
    // 在这里采取记录差异法来进行信息的动态修改
    const originalUser = userStore().userInfo;
    const updatedFields: Record<string, string> = {};

    modifiedFields.forEach((field: string) => {
        const currentValue = userInfo.value[field];
        const originalValue = originalUser[field];
        if (field in originalUser) {
            // 在这里需要确保值是字符串类型
            const currentStringValue = typeof currentValue === 'string' ? currentValue : String(currentValue);
            const originalStringValue = typeof originalValue === 'string' ? originalValue : String(originalValue);
            // 这里的报红不改也行       能跑不就行了
            if (JSON.stringify(currentStringValue) !== JSON.stringify(originalUser[field])) {
                updatedFields[field] = currentStringValue;        // 记录变更的字段
            }
        } else {
            ElMessage.warning("不存在啊！");
        }
    })

    // 如果字段有变更才进行更新操作
    if (Object.keys(updatedFields).length > 0) {
        try {
            const response = await axiosInstance.post(`http://localhost:8080/camelia/update`, {
                updateFields: updatedFields
            }, {
                headers: {
                    'Content-Type': 'application/json'
                },
                params: {
                    userId: userStore().userInfo.uu_id
                }
            })
            // 更新pinia store中的用户信息，完成同步
            const userStoreInstance = userStore();
            for (const field in updatedFields) {
                userStoreInstance.userInfo[field] = updatedFields[field];
            }
            ElMessage.info(`${response}`)
        } catch (error) {
            console.error(error);
        }
    }

}




</script>



<style scoped lang="scss">
@import url("./user.scss");
</style>
